package com.dunqi.gpm.cangxi.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.dunqi.gpm.cangxi.KongApp;
import com.dunqi.gpm.cangxi.MainActivity;
import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseAct;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.base.Data3;
import com.dunqi.gpm.cangxi.common.util.CommonUtil;
import com.dunqi.gpm.cangxi.common.util.LogUtils;
import com.dunqi.gpm.cangxi.common.util.SPHelper;
import com.dunqi.gpm.cangxi.common.util.SharedPreferencesUtils;
import com.dunqi.gpm.cangxi.common.util.SignatureUtil;
import com.dunqi.gpm.cangxi.common.util.TimeUtil;
import com.dunqi.gpm.cangxi.mine.bean.User;
import com.dunqi.gpm.cangxi.mine.util.JpushUtil;
import com.dunqi.gpm.cangxi.mine.util.UserUtil;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;

public class LoginActivity extends BaseAct {

    public static final String USER_TAGS = "user_tags";
    @BindView(R.id.username_edit)
    EditText usernameEdit;
    @BindView(R.id.password_edit)
    EditText passwordEdit;
    @BindView(R.id.vcode_edit)
    EditText vcodeEdit;
    @BindView(R.id.image_iv)
    ImageView imageIv;

    @Override
    protected void refreshData(Bundle savedInstanceState) {
    }

    private void update() {
//        Disposable subscribe = UpgradeUtil.upgradeCheck(this);
//        addDisposables(subscribe);
    }

    @Override
    protected void onPermissionSuccess(String[] permissions, int requestCode) {
        super.onPermissionSuccess(permissions, requestCode);
        if (requestCode == 121) {
            // update();
        }
    }

    @Override
    protected void onPermissionFailed(int requestCode) {
        super.onPermissionFailed(requestCode);
    }

    @Override
    protected void initUiAndListener() {
        int checkSelfPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int checkREAD_PHONE_STATE = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
//        int size = checkREAD_PHONE_STATE + checkSelfPermission;
//        String[] permissions = new String[Math.abs(size)];
        List<String> list = new ArrayList<String>();
        int size = 0;
        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            size++;
        }
        if (checkREAD_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {
            list.add(Manifest.permission.READ_PHONE_STATE);
            size++;
        }
        String[] permissions = new String[list.size()];
        for (int i = 0; i < size; i++) {
            permissions[i] = list.get(i);
        }
        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            size++;
        }
        if (checkREAD_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {
            list.add(Manifest.permission.READ_PHONE_STATE);
            size++;
        }
        if (permissions != null && permissions.length > 0) {
            ActivityCompat.requestPermissions(this, permissions, READ_PHONE_STATE);
        }
        init();
    }

    int READ_PHONE_STATE = 1031, WRITE_EXTERNAL_STORAGE = 1235;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (READ_PHONE_STATE == requestCode) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        new AlertDialog.Builder(this).setTitle("提示").setMessage("为保障更新功能正常运行,请设置允许读写权限!").setNegativeButton("去设置", (dialog, which) -> {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                            startActivity(intent);
                        }).show();
                    }
                    if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE)) {
                        new AlertDialog.Builder(this).setTitle("提示").setMessage("为了识别您的唯一性,请允许程序读取设备信息!").setNegativeButton("去设置", (dialog, which) -> {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                            startActivity(intent);
                        }).show();
                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    void init() {
        boolean stopped = JPushInterface.isPushStopped(this);
        if (stopped) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("APP注册到消息推送服务器失败，不允许登录，请检查你的手机网络或联系管理员");
            builder.setPositiveButton("确定", (dialog, which) -> finish());
            builder.show();
        } else {
            String appToken = UserUtil.getAppToken();
            User user = UserUtil.getUser();
            if (user != null && !TextUtils.isEmpty(appToken) &&
                    TimeUtil.convertToUnix(user.getTokenExpireDate()) > System.currentTimeMillis()) {
                Set sets = SharedPreferencesUtils.getSetData(USER_TAGS);
                Set set = JpushUtil.setTags(sets);
                checkTagAndStart(set);
                return;
            }
        }
        imageIv.performClick();
        //可有可无吧，之前有问题，后来突然消失，这里稳一波
        setBackground(R.color.color_005fff);

        if (SPHelper.init(LoginActivity.this).getBoolean("remember")) {
            SPHelper.init(LoginActivity.this).put("remember", true);
            String username = SPHelper.init(LoginActivity.this).getString("username");
            String password = SPHelper.init(LoginActivity.this).getString("password");
            usernameEdit.setText(username);
            passwordEdit.setText(password);
        } else if ("no".equals(SPHelper.init(LoginActivity.this).getString("fisrt"))) {
            CheckBox viewById = findViewById(R.id.config_remember);
            viewById.setChecked(false);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.image_iv, R.id.config_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_iv:
//                getVcode();
                break;
            case R.id.config_btn:
                canToMain = true;
                login();
                break;
        }
    }

    @Override
    public View getStateView() {
        return null;
    }

    @SuppressLint("CheckResult")
    private void login() {
        final String username = usernameEdit.getText().toString().trim();
        final String password = passwordEdit.getText().toString().trim();
        String vcode = "kong";//专属标记，网名
        String digestPassword = SignatureUtil.digest(password, null).toLowerCase();
        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在登录...");
        ApiFactory.getInstance()
                .login(username, digestPassword, vcode, CommonUtil.getDeviceId())
                .compose(RxSchedulers.<Data<User>>io_main())
                .subscribe(data -> {
                    dialog.dismiss();
                    int resultCode = data.getResultCode();
                    if (resultCode == 1) {
                        User user = data.getData();
                        List<Data3> data3 = data.getData3();
                        if (data3 != null || !data3.isEmpty()) {
                            for (Data3 data31 : data3) {
                                user.getUserRoles().put(data31.getRoleCode(), data31);
                            }
                            user.setBaseUrl(data.getData2());
                        }
                        UserUtil.saveUser(user);
                        CheckBox viewById = findViewById(R.id.config_remember);
                        SPHelper.init(LoginActivity.this).put("fisrt", "no");
                        if (viewById.isChecked()) {
                            SPHelper.init(LoginActivity.this).put("remember", true);
                            SPHelper.init(LoginActivity.this).put("username", username);
                            SPHelper.init(LoginActivity.this).put("password", password);
                        } else {
                            SPHelper.init(LoginActivity.this).put("remember", false);
                            SPHelper.init(LoginActivity.this).put("username", "");
                            SPHelper.init(LoginActivity.this).put("password", "");
                        }
                        Set<String> strings = JpushUtil.setTags(data3);
                        checkTagAndStart(strings);
                        return;
                    }

                    String resultMessage = data.getResultMessage();
                    if (!TextUtils.isEmpty(resultMessage)) {
                        vcodeEdit.setText("");
                        CommonUtil.showSingleToast(resultMessage);
                    }
                    imageIv.performClick();
                }, throwable -> {
                    t("登录失败");
                    dialog.dismiss();
                    imageIv.performClick();
                    vcodeEdit.setText("");
                });
    }

    /**
     * 检查后台tag是否有效，含有无效的就提示用户
     *
     * @param strings
     */
    private void checkTagAndStart(Set<String> strings) {
        if (strings.isEmpty()) {
            KongApp.finishAllActivity();
            startActivity(new Intent(getActivity(), MainActivity.class));
        } else {
            StringBuilder sb = new StringBuilder("设置用户推送tag:");
            for (String string : strings) {
                sb.append(string);
            }
            sb.append("失败，请联系管理员");
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(sb);
            builder.setPositiveButton("确定", (dialog, which) -> finish());
            builder.show();
        }
    }

    @SuppressLint("CheckResult")
    private void getVcode() {
        ApiFactory.getInstance()
                .getVcode(System.currentTimeMillis())
                .compose(RxSchedulers.<ResponseBody>io_main())
                .subscribe(responseBody -> {
                    Bitmap bitmap = BitmapFactory.decodeStream(responseBody.byteStream());

                    imageIv.setImageBitmap(bitmap);
                }, throwable -> {

                });
    }

    boolean canToMain = true;

    private void checkUpdate() {
        PgyUpdateManager.register(LoginActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        canToMain = false;//有更新不让跳
                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        new android.app.AlertDialog.Builder(LoginActivity.this)
                                .setTitle("新版本")
                                .setMessage(appBean.getReleaseNote())
                                .setNegativeButton(
                                        "更新", (dialog, which) -> {
                                            startDownloadTask(LoginActivity.this, appBean.getDownloadURL());
//                                            int code = 0;
//                                            try {
//                                                code = CommonUtil.getVersionCode();
//                                            } catch (Exception e) {
//                                                e.printStackTrace();
//                                            }
//                                            final int finalCode = code;
//                                            VersionUpdateConfig.getInstance()//获取配置实例
//                                                    .setContext(LoginActivity.this)//设置上下文
//                                                    .setDownLoadURL(appBean.getDownloadURL())//设置文件下载链接
//                                                    .setNewVersion(String.valueOf(finalCode))//设置即将下载的APK的版本号,避免重复下载
//                                                    //.setFileSavePath(getExternalCacheDir())//设置文件保存路径（可不设置）
//                                                    .setNotificationIconRes(R.mipmap.ic_launcher)//设置通知图标
//                                                    .setNotificationSmallIconRes(R.mipmap.ic_launcher)//设置通知小图标
//                                                    .setNotificationTitle("苍溪重点项目")//设置通知标题
//                                                    .startDownLoad();//开始下载
                                        }).show();
                    }

                    @Override
                    public void onNoUpdateAvailable() {
                        LogUtils.w("checkUpdate", "onNoUpdateAvailable");
                        //       Toast.makeText(LoginActivity.this, "没有更新", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        PgyUpdateManager.unregister();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkUpdate();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PgyUpdateManager.unregister();
    }
}